package cn.kgc.shiro01;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/7/27
 * @Description:
 */
public class CustomerRealm extends AuthorizingRealm {
    //  授权方法   用户访问受限资源时 该方法会被自动调用   root ->role    user->role user_role
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("===============授权方法doGetAuthorizationInfo()====================");
        // 1. 根据用户的身份信息 查询用户拥有的权限  角色权限    权限字符串
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // TODO  2.根据用户名 查询数据库  List<Role>   admin
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("customer");

        // 添加用户的权限字符串    权限字符串数据库
        simpleAuthorizationInfo.addStringPermission("user:add");
        simpleAuthorizationInfo.addStringPermission("user:delete");

        return simpleAuthorizationInfo;
    }


    //认证方法  subject.login(token)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("===============认证方法doGetAuthenticationInfo()====================");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        //TODO  根据用户名 查询用户信息  salt
        if("root".equals(username)){
            // 该用户信息 时从数据库中查询数据的封装
           return new SimpleAuthenticationInfo("root","2d8aa1bb8d0828a8414d61ab017d683e", ByteSource.Util.bytes("java2320"),this.getName());
        }
        return null;
    }
}
